<template>
	<view class="service_list">
		<view class="category_label" v-if="orderId">
			<view class="category_label_icon"></view>
			<view class="category_label_text">关联订单</view>
		</view>
		<view class="order-card" v-if="orderId">
			<!-- 订单头部 -->
			<view class="order-header">
				<view class="shop-info">
					<view class="shop-name">{{ orderInfo.studioName }}</view>
					<view class="order-time">{{ orderInfo.orderId }}</view>
				</view>
				<text class="order-status">{{ getStatusText(orderInfo.status) }}</text>
			</view>

			<view class="order_server_info">
				<scroll-view class="multiple_specs_scroll" scroll-x="true" v-if="orderInfo?.orderGoodsSkuVOSAll?.length > 1">
					<view class="server_info_box" v-for="val in orderInfo.orderGoodsSkuVOSAll" :key="val.skuId">
						<image class="server_img" :src="val.goodsAvatar"></image>
						<view class="specs_box">{{ val.goodsName }}</view>
						<view class="server_price">×{{ val.serviceDays || 1 }}</view>
					</view>
				</scroll-view>
				<view class="server_info_box" v-else>
					<image class="server_img" :src="orderInfo?.orderGoodsSkuVOSAll?.[0]?.goodsAvatar"></image>
					<view class="name_price">
						<view class="server_name">{{ orderInfo?.orderGoodsSkuVOSAll?.[0]?.goodsName }}</view>
						<view class="specs_price">
							<text class="server_specs">{{ orderInfo?.orderGoodsSkuVOSAll?.[0]?.serviceTime }} | ¥{{ orderInfo?.orderGoodsSkuVOSAll?.[0]?.price }}</text>
						</view>
					</view>
				</view>
				<view class="order_price_box">
					<view class="order_price">¥{{ orderInfo.payAmount }}</view>
					<view class="pay_text">{{ getPayText(orderInfo.status) }}</view>
				</view>
			</view>

			<view class="order-details">
				<view class="detail-item">
					<view class="label">宠物{{ orderInfo.petNum }}只</view>
					<view class="value">
						<text v-for="(val, valIndex) in orderInfo.petList" :key="valIndex">
							{{ val.petNickName }}({{ getPetTypeText(val.type) }})
							<text style="margin: 0 8rpx" v-if="valIndex < orderInfo.petList.length - 1">|</text>
						</text>
					</view>
				</view>
				<view class="detail-item">
					<view class="label">服务时间</view>
					<view class="value">{{ orderInfo?.serviceEndTime?.substring(0, 10) }} {{ orderInfo.doorTime }}</view>
				</view>
				<view class="detail-item">
					<view class="label">服务地址</view>
					<view class="value">{{ orderInfo.address }}</view>
				</view>
			</view>
		</view>
		
		<view class="empty_box" v-if="extraServiceList.length == 0">
			<view class="empty_content">暂无增值服务</view>
		</view>
		<view class="category_label" v-if="orderId && extraServiceList.length > 0">
			<view class="category_label_icon"></view>
			<view class="category_label_text">选择增值服务</view>
		</view>
		<view class="service-item" v-for="item in extraServiceList" :key="item.id" @tap="handleSelectService(item)">
			<view class="service-item-wrapper" :class="{ active: item.selected && item.config?.length > 0 }">
				<view class="service-content">
					<image class="service-image" :src="item.goods.thumPic" mode="aspectFill" />
					<view class="service-info">
						<text class="service-name">{{ item.goods.name }}</text>
						<text class="service-price">¥{{ item.goodsSkuList[0].price }}/次</text>
					</view>
				</view>
				<view class="service-arrow">
					<image v-if="item.selected" class="arrow-icon" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-13.png" />
					<view v-else class="service-arrow-unselected"></view>
				</view>
			</view>
			<view class="section" v-if="item.selected && item.config?.length > 0">
				<view class="result-list">
					<view v-for="(configItem, configIndex) in item.config" :key="configIndex" class="result-item">
						<view class="pet-name">
							<text v-if="item.goods?.pickServicePet == 1">{{ configItem.petNickName }}</text>
							<text v-if="item.goods?.pickServiceDate == 1 && item.goods?.pickServicePet == 0">{{ configItem.date }}</text>
						</view>
						<view class="date" v-if="item.goods?.pickServicePet == 1 && item.goods?.pickServiceDate == 1">{{ configItem.date }}</view>
					</view>
				</view>
				<view class="service-count">
					<view class="count-info">
						<text class="label">共{{ computedServiceCount(item.config) }}次服务｜总计¥{{ getTotalPrice(item) }}</text>
					</view>
					<view class="edit-btn" @tap.stop="handleEditService(item)">
						修改
						<uni-icons type="right" color="#7C807F" size="16"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		
		<view class="footer_box" v-if="extraServiceList.length > 0">
			<view class="footer_button" @tap="handleSubmit">确认</view>
		</view>
		<ServicePopup ref="servicePopupRef" :serviceInfo="currentService" :petList="petList" :dateList="dateList" @cancel="handleServiceCancel" @confirm="handleServiceConfirm" />
	</view>
</template>

<script setup lang="ts">
import { nextTick, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import api from '@/api';
import BigNumber from 'bignumber.js';
import dayjs from 'dayjs';
import ServicePopup from './components/servicePopup.vue';
import { useOrderStoreToRefs } from '@/store/useOrderStore';
const { serviceDateList, petsInfo, selectedExtraServiceListByStore } = useOrderStoreToRefs();

const servicePopupRef = ref();
const currentService = ref({});
const extraServiceList = ref([]);
const petList = ref([]);
const dateList = ref([]);

// {
//     id: 1,
//     name: "服务1",
//     price: 100,
//     image: "/static/logo.png",
//     config: [{ petId: 1, date: "2025/03/24" }],
//   }
const selectedServiceList = ref([]);
const orderId = ref('');
const orderInfo = ref({});

onLoad(async (options) => {
	if (options.orderId) {
		orderId.value = options.orderId;
		await getOrderInfo();
		await getExtraServiceListByGoodsId(orderInfo.value.goodsId);
		filterExtraServiceInOrder()
		
		dateList.value = [dayjs(orderInfo.value.serviceStartTime).format('YYYY-MM-DD')];
	} else {
		init();
		getExtraServiceListByGoodsId(options.goodsId);
	}
});

const init = async () => {
	petList.value = petsInfo.value;
	dateList.value = serviceDateList.value.map((item) => item.fulldate);
	selectedServiceList.value = selectedExtraServiceListByStore.value;
};

const getOrderInfo = async () => {
	const { data } = await api({
		method: 'get',
		url: `/mall/order/order-detail/dayOrderDetail`,
		data: {
			id: orderId.value
		}
	});
	orderInfo.value = data;
};

const getExtraServiceListByGoodsId = async (goodsId) => {
	const { data } = await api({
		method: 'get',
		url: `/mall/goods/studio-goods/info/v2`,
		data: { id: goodsId }
	});
	
	extraServiceList.value = data?.addServiceList || [];

	extraServiceList.value.forEach((item, index) => {
		const service = selectedServiceList.value.find((selectedService) => selectedService.goods.id == item.goods.id);
		item.selected = service ? true : false;
		item.config = service ? service.config : [];

		// 测试用
		// if (index==0) {
		// 	item.goods.pickServicePet = 1
		// 	item.goods.pickServiceDate = 1
		// }
		// else if (index%2==0) {
		// 	item.goods.pickServicePet = 0
		// 	item.goods.pickServiceDate = 1
		// } else {
		// 	item.goods.pickServicePet = 1
		// 	item.goods.pickServiceDate = 0
		// }
	});
};

const filterExtraServiceInOrder = () => {
	const petNumber = orderInfo.value?.petList?.length;
	
	const allPetList = orderInfo.value?.petList?.map((item) => {
		item.petId = item.id;
		return item;
	});
	const newList = extraServiceList.value.filter(newService => {
		const isPaidServiceInfo = orderInfo.value.orderGoodsSkuVOSAll.find((orderService) => newService.goods.id == orderService.goodsId);
		if (!isPaidServiceInfo) {
			newService.availablePetList = allPetList
			return true;
		}
			
		// 日订单中，不用选宠物则过滤，因为日订单只有一天，也不用选天数
		const situation1 = newService.goods.pickServicePet == 0 && newService.goods.pickServiceDate == 1;
		const situation2 = newService.goods.pickServicePet == 0 && newService.goods.pickServiceDate == 0;
		if (situation1 || situation2) return false
		// 日订单中，选宠物的增值服务中，已选宠物数量和宠物总数相等的过滤，因为没有多余宠物可选
		const isSelectedAllPets = petNumber == isPaidServiceInfo.petVOList.length;
		// const situation3 =  newService.goods.pickServicePet == 1 && newService.goods.pickServiceDate == 0 && isSelectedAllPets;
		// const situation4 =  newService.goods.pickServicePet == 1 && newService.goods.pickServiceDate == 1 && isSelectedAllPets;
		if (isSelectedAllPets) return false;
		
		const filterPetList = orderInfo.value?.petList.filter(petInfo => {
			petInfo.petId = petInfo.id
			const isSelected = isPaidServiceInfo?.petVOList?.some(selectedPet => selectedPet.id == petInfo.id)
			return !isSelected
		})
		newService.availablePetList = filterPetList
		return true
	});
	
	extraServiceList.value = newList || []
}

const getTotalPrice = (data) => {
	const count = computedServiceCount(data.config);
	const result = new BigNumber(data?.goodsSkuList[0]?.price).times(count).toFixed(2);
	return Number(result) || 0;
};

const handleSelectService = (data) => {
	currentService.value = data;
	if (data.goods.pickServiceDate == 1 || data.goods.pickServicePet == 1) {
		if (!data.selected) {
			configureService();
		} else {
			data.selected = false;
			currentService.value.config = [];
		}
	} else {
		data.selected = !data.selected;
	}
};

const handleServiceCancel = () => {};

const handleServiceConfirm = (data) => {
	console.log('handleServiceConfirm', data);
	currentService.value.selected = true;
	currentService.value.config = data;
};

const handleEditService = (data) => {
	currentService.value = data;
	configureService();
};

const configureService = () => {
	const config = currentService.value.config;
	if (orderId.value) {
		petList.value = currentService.value.availablePetList
	}
	nextTick(() => {
		setTimeout(() => {
			servicePopupRef.value.open(config);
		}, 300)
	});
};

const handleSubmit = () => {
	selectedServiceList.value = extraServiceList.value.filter((item) => item.selected);
	selectedExtraServiceListByStore.value = selectedServiceList.value;
	console.log('selectedServiceList', selectedServiceList.value);
	if (orderId.value) {
		uni.navigateTo({
			url: `/pages/payment/extraServiceOrder/index?orderId=${orderId.value}`
		});
	} else {
		uni.navigateBack();
	}
};

// 计算服务次数，按天算，不按宠物算
const computedServiceCount = (data) => {
	const list = data.filter((item) => item.date);
	return list.length || 1;
};

const getPayText = (type) => {
	switch (type) {
		case 4:
		case 5:
			return '合计';
		default:
			return '实付';
	}
};

const getStatusText = (status) => {
	switch (status) {
		case 1:
			return '待服务';
		case 2:
			return '服务中';
		case 3:
			return '已完成';
		case 4:
			return '已取消';
		case 5:
			return '已取消';
		default:
			return '';
	}
};

const getPetTypeText = (type) => {
	switch (type) {
		case 0:
			return '猫';
		case 1:
			return '狗';
		default:
			return '其他';
	}
};
</script>

<style lang="scss" scoped>
.service_list {
	padding: 32rpx;
	background: #f9f6f6;
	min-height: 100vh;
	box-sizing: border-box;
	padding-bottom: calc(134rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(134rpx + env(safe-area-inset-bottom));
}

.category_label {
	display: flex;
	align-items: center;
	margin-bottom: 32rpx;

	.category_label_icon {
		width: 8rpx;
		height: 32rpx;
		background: #ff6084;
		border-radius: 4rpx 4rpx 4rpx 4rpx;
		margin-right: 16rpx;
	}
	.category_label_text {
		font-weight: bold;
		font-size: 36rpx;
		color: #1b2120;
	}
}

.order-card {
	background: #ffffff;
	border-radius: 24rpx;
	padding: 40rpx 32rpx;
	margin-bottom: 48rpx;

	.order-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 48rpx;

		.shop-info {
			line-height: 1;
			.shop-name {
				font-weight: bold;
				font-size: 32rpx;
				color: #1b2120;
				margin-bottom: 16rpx;
			}

			.order-time {
				font-size: 24rpx;
				color: #808080;
			}
		}

		.order-status {
			font-size: 26rpx;
			color: #6363ff;
		}
	}

	.order-content {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;

		.service-image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 16rpx;
			margin-right: 16rpx;
		}

		.service-info {
			flex: 1;

			.service-name {
				font-weight: 500;
				font-size: 32rpx;
				color: #1b2120;
				margin-bottom: 24rpx;
			}

			.service-price {
				font-size: 26rpx;
				color: #7c807f;
			}
		}

		.total-price {
			padding: 26rpx 16rpx;
			text-align: center;
			box-shadow: -8rpx 0 16rpx -8rpx rgba(0, 0, 0, 0.15);

			.price {
				font-weight: bold;
				font-size: 28rpx;
				color: #1b2120;
			}

			.price-label {
				font-size: 24rpx;
				color: #7c807f;
				margin-top: 16rpx;
			}
		}
	}

	.order_server_info {
		display: flex;
		justify-content: space-between;
		margin-top: 48rpx;

		.server_info_box {
			display: flex;
			align-items: center;
			flex-direction: row;
			width: calc(100% - 120rpx - 16rpx);

			.server_img {
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
			}

			.name_price {
				margin-left: 16rpx;
				max-width: calc(100% - 120rpx - 16rpx);

				.server_name {
					font-weight: bold;
					font-size: 32rpx;
					color: #1b2120;
				}

				.specs_price {
					font-weight: 400;
					font-size: 26rpx;
					color: #7c807f;
					margin-top: 24rpx;
					text-overflow: ellipsis;
					white-space: nowrap;
					overflow: hidden;

					.server_specs {
					}

					.server_price {
					}
				}
			}
		}

		.multiple_specs_scroll {
			white-space: nowrap;
			width: calc(100% - 128rpx);

			.server_info_box {
				display: inline-block;
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				position: relative;
				margin-right: 16rpx;

				.server_img {
					width: 120rpx;
					height: 120rpx;
					border-radius: 12rpx;
				}

				.specs_box {
					position: absolute;
					top: 8rpx;
					left: 8rpx;
					max-width: 98rpx;
					background: #f9f6f6;
					border-radius: 4rpx;
					font-weight: 400;
					font-size: 18rpx;
					color: #1b2120;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					padding: 0 4rpx;
				}

				.server_price {
					position: absolute;
					bottom: 0;
					right: 0;
					padding: 8rpx 10rpx;
					box-sizing: border-box;
					background: rgba(0, 0, 0, 0.35);
					border-radius: 24rpx 0rpx 24rpx 0rpx;
					font-weight: bold;
					font-size: 18rpx;
					color: #ffffff;
				}
			}
		}

		.order_price_box {
			width: 128rpx;
			padding: 0 16rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			box-shadow: -12rpx 0 20rpx -18rpx rgba(0, 0, 0, 0.2);

			.order_price {
				font-weight: bold;
				font-size: 28rpx;
				color: #1b2120;
			}

			.pay_text {
				font-weight: 400;
				font-size: 24rpx;
				color: #7c807f;
				margin-top: 16rpx;
			}
		}
	}

	.order-details {
		margin-top: 16rpx;
		padding: 32rpx 24rpx;
		border: 2rpx solid #f9f6f6;
		border-radius: 16rpx 16rpx 16rpx 16rpx;

		.detail-item {
			display: flex;
			margin-bottom: 40rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.label {
				font-weight: bold;
				font-size: 24rpx;
				color: #5c5e5e;
				width: 120rpx;
				flex-shrink: 0;
			}

			.value {
				font-size: 24rpx;
				color: #7c807f;
				flex: 1;
			}
		}
	}
}

.service-item {
	padding: 40rpx 32rpx;
	background: #ffffff;
	border-radius: 24rpx;
	margin-bottom: 32rpx;

	.service-item-wrapper {
		display: flex;
		align-items: center;
		justify-content: space-between;

		&.active {
			padding-bottom: 40rpx;
			margin-bottom: 40rpx;
			border-bottom: 1rpx solid #e4e6e6;
		}
	}

	.service-content {
		display: flex;
		align-items: center;

		.service-image {
			width: 96rpx;
			height: 96rpx;
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			margin-right: 16rpx;
		}

		.service-info {
			.service-name {
				font-weight: bold;
				font-size: 32rpx;
				color: #1b2120;
				margin-bottom: 8rpx;
				display: block;
			}

			.service-price {
				font-size: 26rpx;
				color: #5c5e5e;
			}
		}
	}

	.service-arrow {
		.service-arrow-unselected {
			width: 48rpx;
			height: 48rpx;
			border-radius: 50%;
			box-sizing: border-box;
			border: 1rpx solid #000000;
		}

		.arrow-icon {
			width: 48rpx;
			height: 48rpx;
			border-radius: 50%;
		}
	}
}

.section {
	.result-list {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 24rpx 16rpx;
		padding: 24rpx;
		background-color: #f9f6f6;
		border-radius: 24rpx;
		margin-bottom: 32rpx;

		.result-item {
			position: relative;
			background: #fff;
			padding: 24rpx;
			border-radius: 12rpx;
			border: 1rpx solid #e6e6e6;

			.pet-name {
				flex: 1;
				font-weight: bold;
				font-size: 26rpx;
				color: #1a1a1a;
			}

			.date {
				margin-top: 16rpx;
				font-size: 22rpx;
				color: #7c807f;
			}

			.delete-icon {
				color: #ff5252;
				font-size: 32rpx;
				position: absolute;
				right: 0;
				top: 0;
				transform: translate(50%, -50%);
				z-index: 1;
			}
		}
	}

	.service-count {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #ffffff;

		.count-info {
			display: flex;
			align-items: center;
			gap: 16rpx;

			.label {
				font-weight: bold;
				font-size: 26rpx;
				color: #1a1a1a;
			}
		}

		.edit-btn {
			display: flex;
			align-items: center;
			gap: 4rpx;
			font-size: 26rpx;
			color: #7c807f;
		}
	}
}

.footer_box {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	padding: 6rpx 32rpx;
	padding-bottom: calc(6rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(6rpx + env(safe-area-inset-bottom));
	box-sizing: border-box;
	border-top: 1rpx solid #e4e6e6;
	background-color: #ffffff;
	z-index: 1;

	.footer_button {
		height: 88rpx;
		background: linear-gradient(90deg, #ff6188 0%, #ff5252 100%);
		border-radius: 62rpx;
		font-size: 28rpx;
		color: #ffffff;
		text-align: center;
		line-height: 88rpx;
	}
}

.empty_box {
	border-radius: 24rpx;
	background-color: #fff;
	padding: 100rpx 32rpx;
	text-align: center;
	font-size: 32rpx;
	font-weight: bold;
	color: #1b2120;
	
	.empty_content {
		
	}
}
</style>
